package com.example.video.common.security.handler;

import com.alibaba.fastjson.JSON;
import com.example.video.common.util.ResponsEnum;
import com.example.video.common.util.ResponseWrap;
import com.example.video.common.util.ResponseWrapUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>
 * 认证失败
 * <p/>
 *
 * @author : yj
 */
@Component
public class JsonAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        ResponseWrap<Object> error = ResponseWrapUtil.error(ResponsEnum.ERROR.code, exception.getMessage());
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(error));
        writer.flush();
    }
}
